#!/usr/bin/env python 
# encoding: utf-8 
import os
import sys
"""
@version: v1.0
@author: xover
@contact: xe333@sina.com
@software: PyCharm
@file: 获取错误日志.py
@time: 2020/4/28 0028 15:37
"""
# const
log_path = {'cinder_volume_log': '/var/log/cinder/cinder-volume.log',
            'cinder_api_log': '/var/log/cinder/cinder-api.log',
            'cinder_sch_log': '/var/log/cinder/cinder-scheduler.log',
            'nova_cpu_log': '/var/log/nova/nova-cpu.log',
            'nova_api_log': '/var/log/nova/nova-api.log'}

def func():
    pass


class Main():
    def start(self):
        if sys.version_info > (3, ):
            plan = input('devstack?')
            request_id = input('Request_id: ')
        else:
            plan = raw_input('devstack?')
            request_id = raw_input('Request_id: ')
        if plan:
            for file in os.listdir('.'):
                path = os.path.join('.', file)
                self.search(path, file, request_id)
        else:
            for file, path in log_path.items():
                self.search(path, file, request_id)

    def search(self, path, file, request_id):
        log = open('logconstruct', 'a+')
        try:
            f = open(path, 'r')
        except IOError:
            log.write(path.center(73, '-'))
            log.write('\n')
        else:
            log.write(file.center(73, '-'))
            log.write('\n')
            error_test = False
            for line in f.readlines():
                if error_test and 'ERROR' in line:
                    log.writelines(line)
                    error_test = True
                elif request_id in line:
                    error_test = True
                    log.writelines(line)
                else:
                    error_test = False
        log.write('%s\n' % ('-'*73))


if __name__ == "__main__":
    main = Main()
    main.start()